/**
 * @Title: model.js
 * @Description: model
 * @author: Fanchao
 * @date: 2020/8/25 9:29 下午
 * @version V1.0
 */

import { pathToRegexp } from "path-to-regexp";

import { message } from "antd";
import { getChildCascader } from "utils/index";
import { getDepartmentTreeList, registerStudentUser } from "api/index";


export default {
    namespace: "register",
    state: {
        treeData: []
    },
    reducers: {
        setUnitsTreeData(state, { payload: treeData }) {
            return { ...state, treeData };
        }
    },
    effects: {
        /**
         * @desc 获取单位
         * @param payload
         * @param call
         * @param put
         * @param select
         * @returns {Generator<*, void, *>}
         */* getUnitsTreeData({ payload }, { call, put, select }) {
            const result = yield call(getDepartmentTreeList, payload);
            if (result.status === "success") {
                const data = result.result;
                const treeData = data.map(c => {
                    if (!c.hasLowerDepartment) {
                        return {
                            value: c.departmentId,
                            label: c.departmentName
                        };
                    } else {
                        return {
                            value: c.departmentId,
                            label: c.departmentName,
                            children: getChildCascader(c.lowerDepartmentModel)
                        };
                    }
                });
                yield put({
                    type: "setUnitsTreeData",
                    payload: treeData
                });
            } else {
                message.error(result.message);
            }
        },
        /**
         * @desc 注册
         * @param payload
         * @param callback
         * @param call
         * @param put
         * @param select
         * @returns {Generator<*, void, *>}
         */* registerStudentUser({ payload, callback }, { call, put, select }) {
            const result = yield call(registerStudentUser, payload);
            if (result.status === "success") {
                message.success(`注册${payload.realName}成功`);
                if (callback && typeof callback === "function") {
                    callback(result);
                }
            } else {
                message.error(result.message);
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                if (pathToRegexp("/register").exec(pathname)) {
                    dispatch({
                        type: "getUnitsTreeData",
                        payload: {}
                    });
                }
            });
        }
    }
};
